package com.xxl.job.admin.service.impl;

import com.xxl.job.admin.core.model.CronJob;
import com.xxl.job.admin.core.model.Server;
import com.xxl.job.admin.dao.InitCrontabServiceDao;
import com.xxl.job.admin.dao.ServerDao;
import com.xxl.job.admin.dto.JobResultDTO;
import com.xxl.job.admin.service.InitCrontabService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Timestamp;
import java.util.List;

/**
 * @author wenhonghao
 * @email 18167784149@163.com
 * @description: 初始化定时任务实现类
 */
@Service
public class InitCrontabServiceImpl implements InitCrontabService {
    @Autowired
    private InitCrontabServiceDao initCrontabServiceDao;

    @Autowired
    private ServerDao serverDao;


    @Override
    // 处理初始化任务的逻辑
    public void initializeCronJobs(List<JobResultDTO.CronTaskResult> cronTasks, String serverIp, String serverUser) {
        try {
            // 首先检查服务器是否已经存在
            Server server = serverDao.findByIp(serverIp);
            if (server == null) {
                // 如果服务器不存在，则插入
                server = new Server();
                server.setIp(serverIp);
                server.setOwner("admin"); // 根据实际情况填写
                server.setSystemName("XT0000"); // 根据实际情况填写
                System.out.println("server对象" + server);
                serverDao.insertServer(server);
            }
            Integer serverId = serverDao.findServerIdByIp(serverIp);

            for (JobResultDTO.CronTaskResult cronTask : cronTasks) {
                String schedule = cronTask.getSchedule().trim(); // 去除空格
                String command = cronTask.getCommand().trim();   // 去除空格
                int status = schedule.startsWith("#") ? 0 : 1;

                // 创建 CronJob 对象
                CronJob cronJob = new CronJob();
                cronJob.setServerId(serverId);
                cronJob.setServerUser(serverUser);
                cronJob.setSchedule(schedule);
                cronJob.setCommand(command);
                cronJob.setStatus(status);

                // 查询是否已有相同的任务
                Integer existingJobId = initCrontabServiceDao.findByServerIdAndCommand(serverId, command, schedule, serverUser);
                System.out.println("查询结果: serverId=" + serverId + ", schedule=" + schedule + ", command=" + command + ", serverUser=" + serverUser);
                System.out.println("查询结果id" + existingJobId);
                if (existingJobId == null) {
                    // 插入任务
                    System.out.println("执行插入，CronJob: " + cronJob);
                    initCrontabServiceDao.insert(cronJob);
                } else {
                    // 更新任务
                    cronJob.setId(existingJobId);
                    System.out.println("准备更新 schedule：" + cronJob.getSchedule() + ", command：" + cronJob.getCommand());
                    initCrontabServiceDao.update(cronJob);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("初始化定时任务时出现错误: " + e.getMessage());
        }
    }


}
